package cn.leestudio.leelibrary.rest;

import org.json.JSONException;
import org.json.JSONObject;

import java.security.NoSuchAlgorithmException;

import cn.leestudio.restlib.core.AbsCall;
import cn.leestudio.restlib.core.Md5Util;
import cn.leestudio.restlib.core.RestStatus;

/**
 * 描 述:
 *
 * @author: lihui
 * @date: 2017-12-12 15:32
 */

public class MyCall extends AbsCall {

    private String baseUrl = "";
    private String version = "";
    public static String APP_KEY = "";
    public static String APP_ID = "";
    private static String deviceId = "";
    private static String channel = "";
    private static String time = "";
    private StringBuffer queryStrBuf;

    protected void addCommonQuery(){
        deviceId = "";
        channel = "";
        time = ""+System.currentTimeMillis()/1000;
        setQueryNameAndValue("deviceid",deviceId);
        setQueryNameAndValue("appid",APP_ID);
        setQueryNameAndValue("hash",buildHash(time));
        setQueryNameAndValue("channel",channel);
        setQueryNameAndValue("time",time);
    }

    protected void addCommonHead(){
        setHeadNameAndValue("charset","UTF-8");
        setHeadNameAndValue("User-Agent", "MHA-AL00,MHA-AL00,Android 7.0,WIFI");
        setHeadNameAndValue("AUTH", "");
    }

    @Override
    protected String getBaseUrl() {
        return "";
    }

    @Override
    protected void respFilter(String result) {
        try {
            JSONObject jsonObject = new JSONObject(result);
            int status = jsonObject.optInt("Status");
            if (status == 200 ){
                super.respFilter(jsonObject.opt("Result").toString());
            }else{
                doError(status+"",jsonObject.optJSONObject("Result").optString("ErrorMsg"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
            doError(RestStatus.HTTP_UNDEFINE.value()+"",e.getMessage());
        }

    }

    private  String buildHash(String time){
        try {
            String hashTxt = APP_KEY+version+ service +APP_ID+deviceId+channel+time;
            String result = Md5Util.getMD5(hashTxt);
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }
    }
}
